<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Validator;
use App\Model\About;
class UploadController extends Controller
{
    //
    public function upload(Request $request){
        //        $allowFile = ['image/jpeg','image/png'];
        $file = $request->file('images');
        $type = $request->get('type');
        $name = $file->getClientOriginalName();
//        $mime = $file->getClientMimeType();
        $validator = Validator::make($request->all(),
            [
                'images' => 'required|mimes:jpeg,png|max:2048'
            ]
        );
        if ($validator->fails()) {
            return response(['msg'=> $validator->errors()->first(),'code' => 700]);
        }
        $path = [
            'name' =>  $name ,
            'url' => env('APP_URL').Storage::url($request->file('images')->storeAs('/',$name))
        ];
        $about = About::find(1);
        $allfiles = '';
        if($type == 'logo'){
            $allfiles = [$path];
        }else{
            $old = json_decode($about->$type);
            if(is_array($old)){
                $allfiles = array_merge($old,[$path]);
            }else{
                $allfiles = [$path];
            }

        }
        $about->update([
            "$type" => json_encode($allfiles)
        ]);
        return response(['msg'=>$about->$type,'code' => 200]);
    }
    public function removeFile(Request $request){
        $type = $request->get('type');
        $name = $request->get('fileName');
        $about = About::find(1);
        $image = json_decode($about->$type);
        $new_image = [];
        foreach ($image as $k => $item){
            if($item->name !== $request->get('fileName')){
                array_push($new_image,$item);
            }
        }
        Storage::delete($name);
        $about->update([
            "$type" => json_encode($new_image)
        ]);
        return response(['msg'=>'已删除','code' => 200]);
    }
}
